using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    public partial class PanelLeaseDevices : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private List<JsonData> showSellDevices = new List<JsonData>();

        public static void Open()
        {
            UIManagerComponent.instance.OpenUI<PanelLeaseDevices>(UILayer.Normal, RootComponent.instance, false);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelLeaseDevices>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelLeaseDevices", layer, isFloat);
            BindProperties(transform);

            BtnBack.SetClick(Close);

            BtnCompare.SetClick(() =>
            {
                PanelCompare.Open();
            });
            
            BtnRecords.SetClick(() =>
            {
                PanelLeaseRecoards.Open();
            });

            ScrollView.SetCellUpdateCallback((RectTransform cell, int index) =>
            {
                // "id":16,
                // "icon":"http://8.134.166.57/tiktok.png",
                // "type": 1,
                // "name":"全托管抖音AI机器人",
                // "subtitle":"-M1",
                // "price":100000,
                // "period":30,
                // "profit":10,
                // "desc":"自动化管.....",
                // "buy_max":0,
                // "buy_level":0,
                // "created_at":"0001-01-01T00:00:00Z"

                JsonData data = showSellDevices[index];
                int type = Mathf.Max(1, (int)data["type"]);
                string bgSprite = "";
                switch (type)
                {
                    case 1:
                        //体验版
                        bgSprite = "pic_expbg";
                        break;
                    case 2:
                        //专业版
                        bgSprite = "pic_probg";
                        break;
                    case 3:
                        //旗舰版
                        bgSprite = "pic_ultbg";
                        break;
                }
                cell.Get<GameObject>("CountBar").SetActive(type > 1);
                RectTransform TextPrice = cell.Get<RectTransform>("TextPrice");
                TextPrice.anchoredPosition = new Vector2(type == 1 ? -70 : 150, TextPrice.anchoredPosition.y);
                cell.Get<GameObject>("BtnBg0").SetActive(type == 1);
                cell.Get<GameObject>("BtnBg1").SetActive(type == 2);
                cell.Get<GameObject>("BtnBg2").SetActive(type == 3);
                cell.GetComponent<Image>().sprite = cell.Get<Sprite>(bgSprite);
                cell.Get<Device>("Device").SetInfo(type, (int)data["period"], false);
                cell.Get<CButton>("BtnDetail").text.text = CommAssets.instance.I18N_detail;
                cell.Get<Text>("TextTitle").text = Utils.GetI18N(data["name"].ToString());
                cell.Get<Text>("TextTitleSub").text = CommAssets.instance.I18N_pre_income + ":" + StringHelper.SurportSpace(data["subtitle"].ToString());
                var inputField = cell.Get<InputField>("InputNum");
                inputField.SetInputAction(input =>
                {
                    if (int.TryParse(inputField.text, out int value))
                    {
                        data["num"]= Mathf.Clamp(value, 1, Config.LeaseMaxOneTimes);
                        inputField.text = data["num"].ToString();
                        cell.Get<Text>("TextPrice").text = $"{I18N.Currency} {StringHelper.Format2Decimal((int)data["price"] * 0.01f * (int)data["num"])}";
                    }
                }, true);
                if (!data.Contains("num"))
                {
                    data["num"] = 1;
                }
                inputField.text = data["num"].ToString();
                cell.Get<CButton>("BtnSub").SetClick(() =>
                {
                    if (inputField.text == "")
                    {
                        inputField.text = "1";
                    }
                    if (int.Parse(inputField.text) > 1)
                    {
                        inputField.text = (int.Parse(inputField.text) - 1).ToString();
                    }
                });
                cell.Get<CButton>("BtnAdd").SetClick(() =>
                {
                    if (inputField.text == "")
                    {
                        inputField.text = "1";
                    }
                    inputField.text = Mathf.Min(Config.LeaseMaxOneTimes, int.Parse(inputField.text) + 1).ToString();
                });
                inputField.shouldHideMobileInput = false;
                string price = StringHelper.Format2Decimal((int)data["price"] * 0.01f * (int)data["num"]);
                cell.Get<Text>("TextPrice").text = $"{I18N.Currency} {price}";
                cell.Get<CButton>("BtnDetail").SetClick(() => { OpenDetail(data); });
                CButton btnLease = cell.Get<CButton>("BtnLease");
                btnLease.text.text = I18N_lease_atonce;
                btnLease.SetClick(() =>
                {
                    int myLevel = (int)UserInfo.Info["level"];
                    if (myLevel < (int)data["buy_level"])
                    {
                        Dialog.Alert(I18N_level_not_enough);
                        return;
                    }
                    PanelLeasePay.Open(data, null);
                });
            });

            ReqData();
        }

        public void RemoveExpDevices()
        {
            for (int i = 0; i < showSellDevices.Count; i++)
            {
                bool isExp = (int)showSellDevices[i]["type"] == 1;
                if (isExp)
                {
                    showSellDevices.RemoveAt(i);
                }
            }
            ScrollView.SetTotalNumber(showSellDevices.Count);
        }

        private async void ReqData()
        {
            await GlobalData.LoadAllSellDevices();
            showSellDevices.Clear();
            for (int i = 0; i < GlobalData.allSellDevices.Count; i++)
            {
                if (UserInfo.HaveBoughtExpDevice)
                {
                    bool isExp = (int)GlobalData.allSellDevices[i]["type"] == 1;
                    if (isExp)
                    {
                        continue;
                    }
                }
                showSellDevices.Add(GlobalData.allSellDevices[i]);
            }
            ScrollView.SetTotalNumber(showSellDevices.Count);
        }

        private void OpenDetail(JsonData data)
        {
            PanelLeaseDevicesDetail.Open(data);
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
